/**
 * Created by XianTao on 2016/11/26
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.portal.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.lego.util.DateTimeUtil;
import org.lego.util.StringUtil;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class WxJsConfigVo {
    private String corpId;   // 公众号的唯一标识
    private Integer agentId;   // 公众号的应用编号

    private String timestamp;   // 生成签名的时间戳
    private String nonceStr;    // 生成签名的随机串
    private String signature;    // 签名
    private List<String> jsApiList = new ArrayList<String>();   // 需要使用的JS接口列表
    private String url; // 调用微信jssdk的页面url


    /**
     * jsTicket签名算法
     *
     * @param jsTicket
     * @param wxJsConfigVo
     */
    public static WxJsConfigVo sign(String jsTicket, WxJsConfigVo wxJsConfigVo) {
        String nonceStr = StringUtil.getUUID();
        String timestamp = String.valueOf(DateTimeUtil.getCurrentTimeSeconds());
        StringBuilder sb = new StringBuilder();
        sb.append("jsapi_ticket=").append(jsTicket)
                .append("&noncestr=").append(nonceStr)
                .append("&timestamp=").append(timestamp)
                .append("&url=").append(wxJsConfigVo.getUrl());
        String signature;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(sb.toString().getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        wxJsConfigVo.setNonceStr(nonceStr);
        wxJsConfigVo.setTimestamp(timestamp);
        wxJsConfigVo.setSignature(signature);
        return wxJsConfigVo;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}
